package com.lyf.controller;

import com.lyf.entity.User;
import com.lyf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    //修改用户
    @PostMapping("update")
    public Map<String,Object> update(@RequestBody User user){
        Map<String, Object> map = new HashMap<>();
        try{
            userService.update(user);
            map.put("success",true);
            map.put("msg","用户更新成功");
        }catch (Exception e) {
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","用户更新失败");
        }

        return map;
    }

    //查找一个
    @GetMapping("findOne")
    public User findOne(String id){
        return userService.findById(id);
    }

    //删除用户
    @GetMapping("delete")
    public Map<String,Object> delete(String id){
        Map<String,Object> map = new HashMap<>();
        try{
            userService.delete(id);
            map.put("success",true);
            map.put("msg","删除成功");
        }catch(Exception e){
            e.printStackTrace();
            map.put("msg","删除失败");
        }
        return map;
    }

    //查询所有
    @GetMapping("findAll")
    public Map<String,Object> findAll(Integer page, Integer rows){
        Map<String,Object> map = new HashMap<>();
        List<User> result = userService.findAll();

        map.put("total",10);
        map.put("totalPage",1);
        map.put("page",page);
        map.put("rows",rows);
        map.put("result",result);

        return map;
    }
    //添加用户
    @PostMapping("add")
    public Map<String,Object> add(@RequestBody User user){//axios的数据都是json
        Map<String, Object> map = new HashMap<>();
        try{
            userService.save(user);
            map.put("success",true);
            map.put("msg","添加用户信息成功");
        } catch(Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","添加用户失败" + e.getMessage());
        }
        return map;
    }
}
